<template>
  <el-dialog
    v-model="visible"
    :title="isLogin ? '管理员登录' : '修改学生信息'"
    width="400px"
    @close="resetForm"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <template v-if="!isLogin && student">
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="student.name" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="student.grade" />
        </el-form-item>
        <el-form-item label="班级" prop="class">
          <el-input v-model="student.className" />
        </el-form-item>
      </template>

      <template v-if="isLogin">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <!-- <el-button v-if="isLogin" @click="testConnection" :loading="testing" type="info">
          测试连接
        </el-button> -->
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isLogin ? '登录' : '保存' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/store/auth'
import { useStudentStore } from '@/store/student'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: 'login' // 'login' or 'edit'
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const authStore = useAuthStore()
const studentStore = useStudentStore()

const formRef = ref()
const loading = ref(false)
const testing = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isLogin = computed(() => props.mode === 'login')

const form = ref({
  username: '',
  password: ''
})

const student = ref(null)

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const resetForm = () => {
  form.value = {
    username: '',
    password: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const testConnection = async () => {
  testing.value = true
  try {
    console.log('🔧 测试后端连接...')

    const response = await request.get('/health/ping')
    console.log('✅ 后端连接成功:', response)
    ElMessage.success('后端连接正常！')

  } catch (error) {
    console.error('❌ 后端连接失败:', error)

    let errorMessage = '后端连接失败'
    if (error.code === 'ECONNREFUSED') {
      errorMessage = '无法连接到后端服务，请确保后端已启动（端口8765）'
    } else if (error.code === 'NETWORK_ERROR') {
      errorMessage = '网络错误，请检查网络连接'
    } else if (error.message) {
      errorMessage = `连接失败: ${error.message}`
    }

    ElMessage.error(errorMessage)
  } finally {
    testing.value = false
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (isLogin.value) {
      await authStore.login(form.value)
      //ElMessage.success('登录成功')
      // 获取学生信息
      await studentStore.fetchStudentInfo()
    } else {
      await studentStore.updateStudentInfo(student.value)
      ElMessage.success('信息更新成功')
    }

    visible.value = false
    emit('success')
  } catch (error) {
    console.error('操作失败:', error)

    // 优化错误提示
    let errorMessage = '操作失败'

    if (error.response) {
      // 服务器返回了错误状态码
      const status = error.response.status
      const data = error.response.data

      if (status === 401) {
        errorMessage = '用户名或密码错误'
      } else if (status === 403) {
        errorMessage = '访问被拒绝'
      } else if (status === 404) {
        errorMessage = '接口不存在，请检查后端服务'
      } else if (status === 500) {
        errorMessage = '服务器内部错误'
      } else if (data && data.message) {
        errorMessage = data.message
      } else {
        errorMessage = `请求失败 (${status})`
      }
    } else if (error.request) {
      // 请求发出但没有收到响应
      errorMessage = '网络连接失败，请检查后端服务是否启动'
    } else if (error.message) {
      // 其他错误
      errorMessage = error.message
    }

    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// 如果是编辑模式，加载学生信息
if (!isLogin.value) {
  studentStore.fetchStudentInfo().then(() => {
    student.value = { ...studentStore.student }
  })
}
</script>